#!/bin/bash

CONFIG_INI_FILE=$1

if ! [ -a "${CONFIG_INI_FILE}" ];
then
  echo "config not exist!"
  exit 1
fi

exportParams(){
  PARAM_FILE=$1
  ! [ -a ${PARAM_FILE} ] && return 1
  PARAMS=($(cat ${PARAM_FILE} | grep -v '#' | awk NF))
  for PARAM in "${PARAMS[@]}"
  do
    KEY=$(echo "${PARAM}" | awk -F '=' '{print $1}')
    VALUE=$(echo "${PARAM}" | awk -F '=' '{print $2}')
    eval "${KEY}=${VALUE}"
  done
}
exportParams ${CONFIG_INI_FILE}

DEPLOY_ARCHIVED_FILE_DIR=${PROJECT_DIR}/jenkins_deploy/${DEPLOY_FILE_DIR_NAME}/archived
OLD_IFS="$IFS";IFS=",";modules=(${modules});IFS="$OLD_IFS"
modules_path=()

if [ ! -n "${PROJECT_DIR}" ] || [ ! -n "${DEPLOY_ARCHIVED_FILE_DIR}" ];
then
  echo "need param PROJECT_DIR or DEPLOY_ARCHIVED_FILE_DIR"
  exit 1
fi

if [ ${MICROSERVICE_ARC} == YES ];
then
  for module in "${modules[@]}"
    do
      modules_path=(${modules_path[@]} ${PROJECT_DIR}/${module})
    done
else
  #非微服务架构处理方式
  modules=(${modules[0]})
  modules_path=(${PROJECT_DIR})
fi

#创建archived文件夹
mkdir -p ${DEPLOY_ARCHIVED_FILE_DIR}

#提取生成的 jar 与 配置文件
echo "start archive"
for ((i = 0; i < ${#modules[@]}; ++i)); do
  TARGET_DIR=${modules_path[i]}/target
  if [ -d ${TARGET_DIR} ] && [ -n "$(find ${TARGET_DIR} -maxdepth 1 -name "${modules[i]}*.jar" -print -quit)" ];
  then
    mkdir -p "${DEPLOY_ARCHIVED_FILE_DIR}/${modules[i]}"
    rm -rf ${DEPLOY_ARCHIVED_FILE_DIR:?}/${modules[i]:?}/*
    #copy jar
    mv ${TARGET_DIR}/${modules[i]}*.jar ${DEPLOY_ARCHIVED_FILE_DIR}/${modules[i]}/${modules[i]}.jar
    #copy 配置文件
    if [ ${COLLECT_APPLICATION_PROPS} == YES ];
    then
      cp ${modules_path[i]}/src/main/resources/${CONFIG_FILE_NAME} ${DEPLOY_ARCHIVED_FILE_DIR}/${modules[i]}/${modules[i]}.properties
    fi
  fi
done
